import { Route, Redirect, RouteProps } from 'react-router-dom';
import { hasToken } from '../../utils/storage';

export type LocationState = {
  from: string;
};

export default function AuthRoute({ path, component: Component, ...restProps }: IAuthProps) {
  if (!Component) {
    console.warn('鉴权路由组件，必须传递component属性 ');
    return null;
  }

  return (
    <Route
      path={path}
      {...restProps}
      render={(_props: any) => {
        if (hasToken()) {
          return <Component {..._props} />;
        }

        return <Redirect to={{ pathname: '/login', state: { from: path } as LocationState }} />;
      }}
    />
  );
}
interface IAuthProps extends RouteProps {}
